﻿/*
 * Created by SharpDevelop.
 * User: Rogerio
 * Date: 05/01/2009
 * Time: 11:23
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

using ComponentFactory.Krypton.Toolkit;

namespace csharp.rad.activation
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		String fileName = Application.StartupPath+"\\license.txt";
		//TODO: PEgar nome do sistema automaticamente do assembly
		string systemName;
		int resetsNumber;
		
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
		}
		
	[DllImport("activation.dll")]
   	public static extern String getCpuId();
   	
   	[DllImport("activation.dll")]
   	public static extern String validateProtection(String fileName, String systemName);
   	
   	[DllImport("activation.dll")]
   	public static extern bool createTrialProtection(String fileName, String systemName, int numberDays);
   	
   	[DllImport("activation.dll")]
   	public static extern String getParam(String fileName, String systemName, String param);
   	
   	[DllImport("activation.dll")]
   	public static extern bool setParam(String fileName, String systemName, String param, String value);
   	
   	[DllImport("activation.dll")]
   	public static extern String setParamEncrypted(String fileName, String systemName, String param, String value);
   	
   	[DllImport("activation.dll")]
   	public static extern String getExpirationDate(String fileName, String systemName);					
		
		void MainFormLoad(object sender, EventArgs e)
		{
			systemName =Application.StartupPath;
			systemName = systemName.Substring(systemName.LastIndexOf("\\")+1);
			String aux = getParam(fileName, systemName, Constant.paramResets);
			if (aux.Equals(String.Empty))
				aux = "0";
			resetsNumber = Convert.ToInt32(aux);
			
			this.Text = this.Text + " - " + systemName;
			if (File.Exists(fileName))
			{
				try
				{
					validateProtection(fileName, systemName);
					
					txtName.Text 	 	= getParam(fileName, systemName, Constant.paramCustomer);
					txtCpfCnpj.Text 	= getParam(fileName, systemName, Constant.paramCpfCnpj);
					txtEmail.Text 	 	= getParam(fileName, systemName, Constant.paramEmail);
					
					txtSerieNumber.Text = getParam(fileName, systemName, Constant.paramSeries) + 
										  "-" +
										  resetsNumber;
					
					txtInstalationDate.Text= getParam(fileName, systemName, Constant.paramInstalationDate);
					txtValidade.Text = getExpirationDate(fileName, systemName);
					
					
					//TODO: gerar número de autenticação
					
					txtName.ReadOnly			= true;
					txtCpfCnpj.ReadOnly			= true;
					txtEmail.ReadOnly			= true;
					txtSerieNumber.ReadOnly 	= true;
					txtValidade.ReadOnly 		= true;
				}
				catch(Exception ee)
				{
					KryptonMessageBox.Show("Erro:\n"+ee.Message);
				}
			}
		}
		
		void BtnOkClick(object sender, EventArgs e)
		{
			if (!File.Exists(fileName))
			{
				//createTrialProtection(fileName,  systemName, 10);
			}
			else
			{
				//setParam(fileName, systemName, Constant.paramSeries,   txtSerieNumber.Text);
				if( !txtVerificationCode.Text.Equals(String.Empty))
				{
					try
					{
						String verificationCode = "";
						if( txtVerificationCode.Text.Contains("-"))
							verificationCode = txtVerificationCode.Text.Trim().Substring(0, txtVerificationCode.Text.IndexOf('-'));
						else
							verificationCode = txtVerificationCode.Text;
						
						string paramResets = getParam(fileName, systemName, Constant.paramResets);
						string paramInstalationDate = getParam(fileName, systemName, Constant.paramInstalationDate);
						string paramCustomer = getParam(fileName, systemName, Constant.paramCustomer);
						string paramEmail = getParam(fileName, systemName, Constant.paramEmail);
						string paramCpfCnpj= getParam(fileName, systemName, Constant.paramCpfCnpj);
	
						if( File.Exists(fileName))
							File.Delete(fileName);
						
						int daysNumber= 0; //Convert.ToInt32(csharp.common.Util.decrypt(verificationCode));
						
						createTrialProtection(fileName,  systemName, daysNumber);
						
						setParam(fileName, systemName, Constant.paramKey, 		 verificationCode);
						setParam(fileName, systemName, Constant.paramResets, Convert.ToString(Convert.ToInt16(paramResets) + 1));
						setParam(fileName, systemName, Constant.paramInstalationDate, paramInstalationDate);
						setParam(fileName, systemName, csharp.common.CONSTANTS.paramCustomer, paramCustomer);
						setParam(fileName, systemName, csharp.common.CONSTANTS.paramCpfCnpj, paramCpfCnpj);
						setParam(fileName, systemName, csharp.common.CONSTANTS.paramEmail, paramEmail);
					}
					catch(Exception ee)
					{
						KryptonMessageBox.Show("Erro:\n"+ee.Message);	
					}
				}
				//setParam(fileName, systemName, Constant.paramCustomer, "José Rogério");
				
	  /* setParam(fileName, systemName,paramSystem           = "sistema";
	   setParam(fileName, systemName,paramSeries           = "serie";
	   setParam(fileName, systemName,paramType             = "tipo";
	   setParam(fileName, systemName,paramKey              = "chave";
	   setParam(fileName, systemName,paramLastKeyDate      = "data_ultima_chave";
	   setParam(fileName, systemName,paramResets           = "resets";
	   setParam(fileName, systemName,paramLastExecutionDate= "data_ultima_execucao";
	   setParam(fileName, systemName,paramInstalationDate  = "data_instalacao";
	   setParam(fileName, systemName,paramCustomer         = "cliente";
	   setParam(fileName, systemName,paramCpuId            = "cpuid";
	   setParam(fileName, systemName,paramEmail            = "email";
	   setParam(fileName, systemName,paramCpfCnpj          = "cpf_cnpj";*/					
			}
			this.Close();
		}
		
		void BtnValidateClick(object sender, EventArgs e)
		{
 			string result;
   			DateTime today, aux;
   			int cont;
   		
			if (File.Exists(fileName))
			{
				string customer= getParam(fileName, systemName, Constant.paramCustomer);
				string serie= getParam(fileName, systemName, Constant.paramSeries);
				string key= getParam(fileName, systemName, Constant.paramKey);
				string cpuid= getParam(fileName, systemName, Constant.paramCpuId);
				string system= getParam(fileName, systemName, Constant.paramSystem);
				string expiration = getExpirationDate(fileName, systemName);
				
				result = validateProtection(fileName, systemName);

				if (result.Equals(common.CONSTANTS.protectionOk))
				{
					KryptonMessageBox.Show("Proteção Ok!");
					if (true)
					{
						aux = Convert.ToDateTime(getExpirationDate(fileName, systemName));
						today= DateTime.Now;
						
						cont = aux.Subtract(today).Days;
						if (cont <= 7)
						{
							KryptonMessageBox.Show("Chave expira em "+cont+" dias, contacte o suporte!");
						}
					}
					//return true;
				}
				else if (result.Equals(common.CONSTANTS.protectionError))
				{
					KryptonMessageBox.Show("Erro de proteção, contacte o suporte!");
					//return false;
				}
				else if (result.Equals(common.CONSTANTS.protectionExpired))
				{
					KryptonMessageBox.Show("Chave de licença expirada, contacte o suporte!");
					//return false;
				}
				else if (result.Equals(common.CONSTANTS.protectionExpireToday))
				{
					KryptonMessageBox.Show("Chave de licença expira hoje, contacte o suporte!");
					//return true;
				}
				else if (result.Equals(common.CONSTANTS.protectionCpuIdError))
				{
					KryptonMessageBox.Show("Erro de proteção 1240, contacte o suporte!");
					//return false;
				}	
				else
				{
					KryptonMessageBox.Show("Erro de proteção indefinido, contacte o suporte!");
				}
			}
			else
				KryptonMessageBox.Show("Chave de licença inexistente!");
			//return false;			
		}
		
		void KryptonButton3Click(object sender, EventArgs e)
		{
			this.Close();
		}
	}
}
